package com.pj.wisdomlogistics.ui.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.pj.spinnerlib.views.NiceSpinner;
import com.pj.wisdomlogistics.MyApplication;
import com.pj.wisdomlogistics.R;
import com.pj.wisdomlogistics.cons.Cons;
import com.pj.wisdomlogistics.mvp.contract.ApplyMealContract;
import com.pj.wisdomlogistics.mvp.frame.MvpActivity;
import com.pj.wisdomlogistics.mvp.frame.base.BaseView;
import com.pj.wisdomlogistics.mvp.presenter.ApplyMealPresenter;
import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.ui.view.AutoRadioGroup;
import com.pj.wisdomlogistics.utils.ActivityManagerUtil;
import com.pj.wisdomlogistics.utils.CustomToast;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;

public class ApplyMealActivity extends MvpActivity<ApplyMealPresenter> implements ApplyMealContract.View, OnDateSetListener {

    @BindView(R.id.tv_apply_dept)
    TextView mTvApplyDept;
    @BindView(R.id.tv_apply_dept_contacts)
    TextView mTvApplyDeptContacts;
    @BindView(R.id.tv_apply_dept_call)
    TextView mTvApplyDeptCall;
    @BindView(R.id.tv_apply_dept_phone)
    TextView mTvApplyDeptPhone;
    @BindView(R.id.rb_meal_type_1)
    RadioButton mRbMealType1;
    @BindView(R.id.rb_meal_type_2)
    RadioButton mRbMealType2;
    @BindView(R.id.sp_meal_standard)
    NiceSpinner mSpMealStandard;
    @BindView(R.id.et_meal_reason)
    EditText mEtMealReason;
    @BindView(R.id.et_meal_count)
    EditText mEtMealCount;
    @BindView(R.id.tv_meal_time)
    TextView mTvMealTime;
    @BindView(R.id.rg_meal)
    AutoRadioGroup mRgMeal;
    @BindView(R.id.ll_meal_standard)
    LinearLayout mLlMealStandard;
    @BindView(R.id.tv_meal_leader)
    TextView mTvLeader;
    @BindView(R.id.ll_isSpecial)
    LinearLayout mLlIsSpecial;
    @BindView(R.id.et_meal_remark)
    TextView mTvRemark;
    @BindView(R.id.rb_place_zf)
    RadioButton mRbPlaceZf;
    @BindView(R.id.rb_place_shy)
    RadioButton mRbPlaceShy;

    long tenYears = 10L * 365 * 1000 * 60 * 60 * 24L;

    private String leaderId = "";
    private String leaderName = "";

    @Override
    protected BaseView getBaseView() {
        return this;
    }

    @Override
    public void initView() {
        ultimateBar.setColorBar(ContextCompat.getColor(this, R.color.text_blue));

        mTvApplyDept.setText(MyApplication.user.getDeptName());
        mTvApplyDeptContacts.setText(MyApplication.user.getName());
        mTvApplyDeptCall.setText(MyApplication.user.getTelphone());
        mTvApplyDeptPhone.setText(MyApplication.user.getMobile());

        mSpMealStandard.attachDataSource(Arrays.asList(getResources().getStringArray(R.array.meal_standard)));

        mRgMeal.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_meal_type_3) {
                    mLlMealStandard.setVisibility(View.GONE);
                    mSpMealStandard.setVisibility(View.GONE);
                    mLlIsSpecial.setVisibility(View.GONE);
                } else {
                    mLlMealStandard.setVisibility(View.VISIBLE);
                    mSpMealStandard.setVisibility(View.VISIBLE);
                    if(MyApplication.user.getIsSpecial() != 1){
                        mLlIsSpecial.setVisibility(View.VISIBLE);
                    }
                }


            }
        });

        //四办人员，不需要区领导签字
        if (MyApplication.user.getIsSpecial() == 1) {
            mLlIsSpecial.setVisibility(View.GONE);
        }


    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentView() {
        return R.layout.activity_apply_meal;
    }

    @Override
    public boolean isApplyEventBus() {
        return true;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {
        if (eventCenter.getEventCode() == Cons.MealInfo.LEADER_ID) {
            String[] str = ((String) eventCenter.getData()).split(",");
            leaderId = str[0];
            leaderName = str[1];
            mTvLeader.setText(leaderName);
        }
    }


    @OnClick({R.id.iv_back, R.id.tv_send, R.id.tv_meal_time, R.id.tv_meal_leader, R.id.iv_remark})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                ActivityManagerUtil.create().finishActivity();
                break;
            case R.id.tv_send:
                int diningType = mRgMeal.getCheckedRadioButtonId() == R.id.rb_meal_type_1 ? 0 : mRgMeal.getCheckedRadioButtonId() == R.id.rb_meal_type_2 ? 1 : 2;
                int diningBenchmark = mRgMeal.getCheckedRadioButtonId() == R.id.rb_meal_type_3 ? 4 : mSpMealStandard.getSelectedIndex();
                String diningReason = mEtMealReason.getText().toString().trim();
                int peopleCount = TextUtils.isEmpty(mEtMealCount.getText().toString().trim()) ? 0 : Integer.parseInt(mEtMealCount.getText().toString().trim());
                String diningTime = mTvMealTime.getText().toString().trim();
                String remark = mTvRemark.getText().toString().trim();
                String place = mRbPlaceZf.isChecked() ? "1" : "2";

                if (TextUtils.isEmpty(diningReason)) {
                    CustomToast.showToast(this, "请输入用餐事由", 1000);
                    return;
                }

                if (peopleCount == 0) {
                    CustomToast.showToast(this, "请输入用餐人数", 1000);
                    return;
                }

                if (TextUtils.isEmpty(diningTime)) {
                    CustomToast.showToast(this, "请选择用餐时间", 1000);
                    return;
                }

                if (TextUtils.isEmpty(leaderName) && MyApplication.user.getIsSpecial() != 1) {
                    CustomToast.showToast(this, "请选择区领导", 1000);
                    return;
                }

                mPresenter.submitDiningApply(
                        MyApplication.userID,
                        MyApplication.user.getDept_id(),
                        MyApplication.user.getName(),
                        MyApplication.user.getMobile(),
                        MyApplication.user.getTelphone(),
                        diningType,
                        diningBenchmark,
                        diningReason,
                        peopleCount,
                        diningTime,
                        leaderId,
                        remark,
                        place
                );

                showProgressDialog();

                break;
            case R.id.tv_meal_time:
                TimePickerDialog mDialogAll = new TimePickerDialog.Builder()
                        .setCallBack(this)
                        .setCancelStringId("取消")
                        .setSureStringId("确认")
                        .setTitleStringId("用餐时间")
                        .setYearText("年")
                        .setMonthText("月")
                        .setDayText("日")
                        .setHourText("时")
                        .setMinuteText("分")
                        .setCyclic(false)
                        .setMinMillseconds(System.currentTimeMillis())
                        .setMaxMillseconds(System.currentTimeMillis() + tenYears)
                        .setCurrentMillseconds(System.currentTimeMillis())
                        .setThemeColor(getResources().getColor(R.color.text_blue))
                        .setType(Type.ALL)
                        .setWheelItemTextNormalColor(getResources().getColor(R.color.text_gray))
                        .setWheelItemTextSelectorColor(getResources().getColor(R.color.text_normal))
                        .setWheelItemTextSize(12)
                        .build();
                mDialogAll.show(getSupportFragmentManager(), "all");
                break;
            case R.id.tv_meal_leader:
                startActivity(QuLeaderActivity.class);
                break;
            case R.id.iv_remark:
                ImageView mImageView = new ImageView(this);
                mImageView.setImageResource(R.drawable.note3);
                mImageView.setScaleType(ImageView.ScaleType.FIT_XY);

                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                AlertDialog ad = builder.create();
                ad.setCanceledOnTouchOutside(true);
                ad.setView(mImageView);
                ad.show();
                break;
        }
    }

    @Override
    public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
        mTvMealTime.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date(millseconds)));
    }

    @Override
    public void onError(String errorMsg) {
        dismissProgressDialog();
        CustomToast.showToast(this, errorMsg, 1000);
    }

    @Override
    public void onSuccess(int id) {
        dismissProgressDialog();
        Intent mIntent = new Intent(this, SuccessActivity.class);
        mIntent.putExtra(Cons.MealInfo.MEAL_ID, id);
        startActivity(mIntent);
        ActivityManagerUtil.create().finishActivity();
    }
}
